<template>
  <el-upload class="upload-wrapper"
             :action="action"
             :on-success="handleSuccess"
             :before-upload="beforeUpload"
             :show-file-list="false">
    <img v-if="singleFile && formItem.type==='singleImage'" :src="singleFile" class="upload-item-image">
    <div v-else-if="singleFile && formItem.type==='singleFile'">
      <i class="el-icon-document"></i>
      <a @click.stop.preven="openFilePath">点击查看</a>
    </div>
    <i v-else class="el-icon-plus image-uploader-icon"></i>
  </el-upload>
</template>

<script>
  import * as api from '../../constants/api';
  import { Message, MessageBox } from 'element-ui'
    export default {
        name: 'Upload',
      props:{
          formItem:{
            type: Object,
            required: true,
          },
        filePath:{
          required: false,
        },
      },
        data() {
            return {
              action: api.UPLOAD,
              singleFile: '',
            }
        },
      created(){
          this.singleFile=this.filePath||'';
      },
      methods:{
        openFilePath(){
          window.open(this.singleFile)
        },
        handleSuccess(res, file){
          // 应该根据res返回真实路径
          if(this.formItem.type==='singleImage' || this.formItem.type==='singleFile') {
            this.singleFile = res;
            this.$emit('uploadSuccess', {name: this.formItem.name, filePath: this.singleFile})
          }
        },
        beforeUpload(file){
          let me = this;
          if(this.formItem.fileTypeList){
            let validExtension= this.formItem.fileTypeList.some(function (item) {
              return file.name.endsWith(item);
            });
            if(!validExtension){
              Message({
                message: `只允许以下格式文件：${me.formItem.fileTypeList}`,
                type: 'error',
                duration: 5 * 1000
              })
              return false;
            }
          }
          if(this.formItem.maxFileSize){
            let validSize = this.formItem.maxFileSize*1024*1024>file.size;
            if(!validSize){
              Message({
                message: `文件大小不能超过 ${me.formItem.maxFileSize}M`,
                type: 'error',
                duration: 5 * 1000
              })
              return false;
            }
          }

          return true;
        }
      }
    }
</script>

<style lang="stylus">
  .upload-wrapper
    .el-upload
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover
        border-color: #409EFF;
      .upload-item-image
        width: 178px;
        height: 178px;
        display: block;
      .image-uploader-icon
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
</style>
